﻿using Microsoft.Phone.Controls;
using System;
using System.Collections.Generic;
using System.Device.Location;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using Windows.Devices.Geolocation;

namespace PhoneMap.Common
{
    public class HandlerRunBackGround : ContentControl
    {
        PhoneApplicationFrame framePage;
        public HandlerRunBackGround(PhoneApplicationFrame frame)
        {
            this.framePage = frame;
            this.framePage.Navigated += framePage_Navigated;
        }
        void framePage_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (App.Geolocator != null)
            {
                App.Geolocator.PositionChanged -= geolocator_PositionChanged;
                App.Geolocator = null;
            }

            App.Geolocator = new Geolocator();
            App.Geolocator.DesiredAccuracy = PositionAccuracy.High;
            App.Geolocator.ReportInterval = (uint)TimeSpan.FromSeconds(30).TotalMilliseconds;
            // App.Geolocator.MovementThreshold = 50; // The units are meters.
            App.Geolocator.PositionChanged += geolocator_PositionChanged;

        }
        private async void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
        {
            if (App.FacebookDatas.id != null)
            {
                App.MyGeoPosition = args.Position;
                if (App.CheckInternet.IsConnected)
                {
                    if (App.RunningInBackground)
                    {
                        Microsoft.Phone.Shell.ShellToast toast = new Microsoft.Phone.Shell.ShellToast();
                        toast.Content = args.Position.Coordinate.Latitude.ToString("0.00");
                        toast.Title = "Location: ";
                        toast.NavigationUri = new Uri("/MainPage.xaml", UriKind.Relative);
                        toast.Show();
                    }
                    Dispatcher.BeginInvoke(() =>
                    {
                        App.mapClient.updatePositionCompleted += mapClient_updatePositionCompleted;
                        var id = long.Parse(App.FacebookDatas.id);
                        App.mapClient.updatePositionAsync(id,float.Parse(args.Position.Coordinate.Latitude.ToString()),
                            float.Parse(args.Position.Coordinate.Longitude.ToString()), DateTime.UtcNow);

                    });
                }
                else
                {
                  await SaveInfo(new BackgroudInfo()
                    {
                        AccountName = App.FacebookDatas.id,
                        Lat = args.Position.Coordinate.Latitude.ToString(),
                        Lon = args.Position.Coordinate.Longitude.ToString()
                    });
                }

            }

        }
        void mapClient_updatePositionCompleted(object sender, MapAPI.updatePositionCompletedEventArgs e)
        {

            App.mapClient.updatePositionCompleted -= mapClient_updatePositionCompleted;
        }
        async Task SaveInfo(BackgroudInfo info)
        {
            var checkData = await StorageProvider.RestoreObjectsAsync<List<BackgroudInfo>>(StorageProvider.BackgroudInfos);
            if (checkData != null && checkData.Count > 0)
            {
                checkData.Add(info);
                await StorageProvider.SaveObjectsAsync<List<BackgroudInfo>>(checkData, StorageProvider.BackgroudInfos);
            }
            else
            {
                List<BackgroudInfo> saveData = new List<BackgroudInfo>();
                saveData.Add(info);
                await StorageProvider.SaveObjectsAsync<List<BackgroudInfo>>(saveData, StorageProvider.BackgroudInfos);
            }
        }
    }
}
